<template>
    <view class="order-detail-main">
        <!--  -->
        <NavBar title="售后详情" :isBack="true" :back="goBack" bgColor="#fe292b" />
        <view class="order-detail-content">
            <!-- 状态信息 -->
            <view class="goods-status-info">
                <view class="goods-status">
                    <view class="goods-status-name">
                        {{ Data.detailInfo?.refundStatusInfo?.refundSubStatusName }}
                    </view>
                    <image
                        v-if="getStatusImg(Data.refundStatus)"
                        class="goods-status-img"
                        :src="getImgOssUrl('/ui-prod-2.0.0/' + getStatusImg(Data.refundStatus))"></image>
                </view>
            </view>

            <view
                v-if="Data.detailInfo?.refundRejectReason && Data.detailInfo?.refundStatusInfo?.refundSubStatus == 9"
                class="reject-reason">
                <text> 拒收原因：{{ Data.detailInfo?.refundRejectReason }} </text>
            </view>

            <!-- 是否退货退款 -->
            <view class="refund-logistics" v-if="Data.refundType == 2 && Data.refundStatus != 1">
                <view class="title">物流信息</view>
                <view class="refund-logistics-info">
                    <view>
                        <view>请将货物寄送至以下地址：</view>
                        <view>
                            {{ Data.refundAddress.provinceIdName }}{{ Data.refundAddress.cityIdName
                            }}{{ Data.refundAddress.areaIdName }}{{ Data.refundAddress.townIdName
                            }}{{ Data.refundAddress.street }}
                        </view>
                        <view>{{ Data.refundAddress.contactPerson }} {{ Data.refundAddress.tel }}</view>
                    </view>
                    <image
                        @click="copyHandler"
                        class="refund-logistics-img"
                        :src="getImgOssUrl('/ui-prod-2.0.0/copy_2.0.png')"></image>
                </view>
                <view class="cell-info">
                    <!--  -->
                    <view>物流公司</view>
                    <picker
                        @change="logisticsPickerChange"
                        :value="Data.logisticsIndex"
                        :range="Data.logisticsList"
                        :disabled="Data.isLogistics"
                        range-key="name">
                        <view class="cell-info-text">
                            <view :class="{ 'text-placeholder': !Data.logisticsName }">
                                {{ Data.logisticsName ? Data.logisticsName : '请选择' }}
                            </view>
                            <image
                                v-if="!Data.isLogistics"
                                class="img-icon"
                                :src="getImgOssUrl('/ui-prod-2.0.0/rightarrow1.1.png')"></image>
                        </view>
                    </picker>
                </view>
                <view class="cell-info">
                    <view>物流单号</view>
                    <input
                        class="cell-info-input"
                        v-model="Data.logisticsNo"
                        :disabled="Data.isLogistics"
                        type="text"
                        maxlength="20"
                        placeholder="请填写物流单号"
                        placeholder-style="color:#ccc" />
                </view>
            </view>
            <view class="refund-price">
                <view class="desc" v-if="Data.refundStatus == 5">商家已同意申请，退款金额将于3个工作日内原路退回</view>
                <view>
                    退回金额：
                    <text class="text" v-if="Data.detailInfo?.refundPaymentFee > 0">
                        ￥{{ floatDivide(Data.detailInfo?.refundPaymentFee, 100) }}
                    </text>
                    <text
                        class="text"
                        v-if="Data.detailInfo?.refundPaymentFee > 0 && Data.detailInfo?.refundUsePoints > 0">
                        +
                    </text>
                    <text v-if="Data.detailInfo?.refundUsePoints > 0" class="text">
                        {{ floatDivide(Data.detailInfo?.refundUsePoints, 100) }}积分
                    </text>
                    <text class="text" v-if="!Data.detailInfo?.refundPaymentFee && !Data.detailInfo?.refundUsePoints">
                        ￥{{ floatDivide(0, 100) }}
                    </text>
                </view>
            </view>
            <!-- 商品信息 -->
            <view class="goods-info">
                <view class="goods-top">
                    <template>
                        <view class="refund-shop-item" v-for="item in Data.goodsList" :key="item.skuId">
                            <GoodsCard v-for="e in item.goods" :key="e.id" :orderType="Data.orderType" :goodsData="e" />
                        </view>
                    </template>
                </view>
                <view class="goods-center"></view>
                <view v-if="!Data.isSelfPickup" class="goods-bottom">
                    <view class="goods-bottom-item">
                        <view>运费</view>
                        <view class="delivery-fee">
                            {{
                                Data.detailInfo.refundLogisticsFee
                                    ? `${floatDivide(Data.detailInfo.refundLogisticsFee, 100)}元运费`
                                    : '￥0'
                            }}
                        </view>
                    </view>
                </view>
            </view>
            <!-- 订单信息 -->
            <view class="order-info">
                <view class="order-info-item">
                    <view class="order-info-label">退货类型</view>
                    <view class="order-info-text">{{ Data.refundTypeName }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">退货理由</view>
                    <view class="order-info-text">{{ Data.detailInfo.reasonCharacter }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">退货说明</view>
                    <view class="order-info-text">{{ Data.detailInfo.description }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">凭证</view>
                    <view class="order-info-text">
                        <view class="refund-img-list">
                            <image
                                class="refund-img"
                                :src="item.imgUrl"
                                v-for="(item, index) in Data.imgList"
                                :key="index"></image>
                        </view>
                    </view>
                </view>
            </view>
            <view class="order-info">
                <view class="order-info-item">
                    <view class="order-info-label">订单号</view>
                    <view class="order-info-text">{{ Data.detailInfo.orderSn }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">退单号</view>
                    <view class="order-info-text">{{ Data.detailInfo.refundNo }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">下单时间</view>
                    <view class="order-info-text">{{ Data.detailInfo.orderCreatedAt }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">申请时间</view>
                    <view class="order-info-text">{{ Data.detailInfo.createdAt }}</view>
                </view>
                <view class="order-info-item">
                    <view class="order-info-label">退款完成时间</view>
                    <view class="order-info-text">{{ Data.refundStatus == 5 ? Data.detailInfo.finishedAt : '' }}</view>
                </view>
            </view>
            <view class="order-button-wrap">
                <view class="order-button">
                    <view
                        class="order-button-item"
                        v-if="Data.refundStatus == 1 || Data.refundStatus == 3"
                        @click="clickRepeal">
                        取消售后
                    </view>
                    <view class="order-button-item" v-if="Data.isLogistics" @click="checkLogisticsInfo">
                        查看物流
                    </view>
                    <view
                        class="order-button-item active"
                        v-if="Data.refundType == 2 && Data.refundStatus == 3"
                        @click="submitLogisticsInfo">
                        提交信息
                    </view>
                </view>
            </view>
        </view>
        <!-- 弹框 -->
        <view class="popup-dialog" v-if="Data.repealShow">
            <view class="popup-dialog-content">
                <view class="title">确认售后撤销？</view>
                <view class="button">
                    <view class="cancel" @click="Data.repealShow = false">取消</view>
                    <view class="confirm" @click="confirmRepeal">确认</view>
                </view>
            </view>
        </view>
        <Loading />
    </view>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import { floatDivide, isNotEmpty, getImgOssUrl } from '@/commons/utils.js';
import router from '@/router';
import request from '@/request';
import store from '@/store';
import NavBar from '@/components/navBar';
import GoodsCard from '@/components/goodsCard';
import Loading from '@/components/el-loading';

const goodsStore = store.useGoodsStore();

const props = defineProps({
    orderId: {
        type: [String, Number],
        default: ''
    },
    type: {
        type: Number
    },
    backType: {
        type: Number,
        default: 1
    }
});

const statusList = [
    {
        name: '退款已申请，待商家审核',
        code: '1',
        img: 'icon_img_status4_1.2.png'
    },
    {
        name: '商家驳回',
        code: '2',
        img: 'icon_img_status4_1.2.png'
    },
    {
        name: '商家审核通过，待寄回商品',
        code: '3',
        img: 'icon_img_status2_1.2.png'
    },
    {
        name: '正在退款',
        code: '4',
        img: 'icon_img_status4_1.2.png'
    },
    {
        name: '退款成功',
        code: '5',
        img: 'icon_img_status3_1.2.png'
    },
    {
        name: '退款失败',
        code: '6'
    },
    {
        name: '撤销申请',
        code: '7'
    }
];

const Data = reactive({
    receiptShow: false,
    repealShow: false,
    detailInfo: {},
    goodsList: [],
    imgList: [],
    refundAddress: {},
    orderType: 1,
    // 是否是自提订单
    isSelfPickup: '',
    isLogistics: false,
    logisticsList: [],
    logisticsIndex: 0,
    logisticsNo: '',
    logisticsName: '',
    logisticsCode: '',
    logisticsId: ''
});

const initDetail = async () => {
    let { orderId } = props;
    let res = await request('refundOrderDetailServ', { refundOrderId: orderId });
    Data.imgList = [];
    let info = res.data || {};
    Data.refundStatus = info.refundStatus;
    Data.detailInfo = info;
    Data.orderType = info.orderType;
    Data.isSelfPickup = Number(info.isSelfPickup);
    rebuildGoodList(info.refundGoods || []);
    Data.orderStatus = info.orderStatus;
    Data.refundType = info.refundType;
    Data.refundAddress = info.refundAddress || {};
    Data.refundTypeName = info.refundType == '1' ? '仅退款' : info.refundType == '2' ? '退货退款' : '';
    if (info.refundProof && info.refundProof.proof) {
        for (let i in info.refundProof) {
            Data.imgList.push({
                imgUrl: info.refundProof[i]
            });
        }
    }
    let logisticsInfo = info.logistics || {};
    Data.isLogistics = isNotEmpty(logisticsInfo);
    Data.logisticsNo = logisticsInfo.logisticsNo;
    Data.logisticsName = logisticsInfo.logisticsCompany;
    Data.logisticsId = logisticsInfo.id;
};

const rebuildGoodList = (arr = []) => {
    Data.goodsList = arr;
    Data.goodsList.forEach(x => {
        x.goods.forEach(e => {
            e.goodsNum = x.refundGoodsCount;
            e.specValueList = e.skuExtInfo;
            e.goodsPrice = Data.orderType === 6 ? e.sellPrice : e.goodsPrice;
            e.goodPoints = Data.orderType === 6 ? e.goodPoints : '';
        });
    });
};

const getLogisticsList = async () => {
    let res = await request('logisticsListServ');
    Data.logisticsList = res.data || [];
};

const logisticsPickerChange = e => {
    let index = e.detail.value;
    Data.logisticsIndex = index;
    Data.logisticsName = Data.logisticsList[index].name;
    Data.logisticsCode = Data.logisticsList[index].code;
};

const copyHandler = () => {
    let text =
        Data.refundAddress.provinceIdName +
        Data.refundAddress.cityIdName +
        Data.refundAddress.areaIdName +
        Data.refundAddress.townIdName +
        Data.refundAddress.street +
        Data.refundAddress.contactPerson +
        Data.refundAddress.tel;
    uni.setClipboardData({
        data: text,
        success: () => {}
    });
};

const checked = () => {
    if (!Data.logisticsName) {
        uni.showToast({
            title: '请选择物流公司',
            icon: 'none'
        });
        return false;
    } else if (!Data.logisticsNo) {
        uni.showToast({
            title: '请填写物流单号',
            icon: 'none'
        });
        return false;
    } else {
        return true;
    }
};

const submitLogisticsInfo = async () => {
    if (!checked()) return;
    let params = {
        orderRefundId: props.orderId,
        logisticsNo: Data.logisticsNo,
        logisticsCompany: Data.logisticsName,
        logisticsCode: Data.logisticsCode,
        logisticsType: 1,
        contactPerson: Data.refundAddress.contactPerson,
        tel: Data.refundAddress.tel,
        provinceIdName: Data.refundAddress.provinceIdName,
        cityIdName: Data.refundAddress.cityIdName,
        areaIdName: Data.refundAddress.areaIdName,
        townIdName: Data.refundAddress.townIdName,
        street: Data.refundAddress.street
    };
    let res = await request('refundOrderLogisticsServ', params);
    if (res.data) {
        uni.showToast({
            title: '提交成功',
            icon: 'none'
        });
        initDetail();
    }
};

const checkLogisticsInfo = () => {
    goodsStore.logisticsGoodsInfo = Data.goodsList[0]?.goods[0];
    router.push({
        path: '/pages-user/logistics/index',
        query: {
            id: Data.logisticsId,
            logisticCompany: Data.logisticsName,
            logisticNo: Data.logisticsNo
        }
    });
};

const clickRepeal = () => {
    Data.repealShow = true;
};

const confirmRepeal = async () => {
    let params = {
        refundOrderId: props.orderId
    };
    let res = await request('refundOrderRepealServ', params);
    if (res.data) {
        Data.repealShow = false;
        uni.showToast({
            title: '取消成功',
            icon: 'none'
        });
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${Data.detailInfo.orderId}`
        });
    }
};

const toLogistics = () => {
    router.push({
        path: '/pages-user/logistics/index',
        query: {
            orderId: props.orderId
        }
    });
};

const goBack = () => {
    router.navigateBack({ delta: props.backType });
};

const toPay = () => {};

const getStatus = code => {
    let list = statusList;
    let obj = list.find(el => el.code == code) || {};
    return obj.name;
};

const getStatusImg = code => {
    let list = statusList;
    let obj = list.find(el => el.code == code) || {};
    return obj.img;
};

onShow(() => {
    getLogisticsList();
    initDetail();
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
